package com.zxc.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxc.demo.dao.ZybDcUserDao;
import com.zxc.demo.model.ZybDcUser;
import com.zxc.demo.service.ZybDcUserService;
import com.zxc.demo.util.AESUtil;
import com.zxc.demo.util.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户信息表zyb_dc_user(ZybDcUser)表服务实现类
 *
 * @author makejava
 * @since 2021-02-22 10:52:30
 */
@Service("zybDcUserService")
public class ZybDcUserServiceImpl extends ServiceImpl<ZybDcUserDao,ZybDcUser> implements ZybDcUserService {
    @Resource
    private ZybDcUserDao zybDcUserDao;
    /**
     * 用户登录
     * @param response
     * @param session
     * @return
     */
    @Override
    public R userLogin(HttpServletResponse response, HttpSession session, String username, String password){
        ZybDcUser user = getOne(new LambdaQueryWrapper<ZybDcUser>()
                .eq(ZybDcUser::getIsDelete,0)
                .eq(ZybDcUser::getUserName, username));
        if (user==null){
            return R.error("500","用户不存在或已禁用");
        }
        if (!password.equals(user.getPassword())){
            return R.error("500","密码错误");
        }
        //登录
        return doLongin(response,session,user);
    }

    /**
     * 登录状态设置
     *
     * @param response
     * @param session
     * @param zybDcUser
     * @return
     */

    private R doLongin(HttpServletResponse response, HttpSession session , ZybDcUser zybDcUser){
        String md5UserName = AESUtil.encrypt(zybDcUser.getMobilePhone());
        Cookie cookie = new Cookie("longin", md5UserName);
        cookie.setPath("/");
        cookie.setHttpOnly(false);
        cookie.setMaxAge(24 * 3600 * 90);
        response.addCookie(cookie);
        session.setAttribute("longin", zybDcUser);
        session.setMaxInactiveInterval(60*60*24*90);
        return R.success(zybDcUser);
    }

}
